from django.shortcuts import render

# Create your views here.
from .models import Test_Case
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from django.http import JsonResponse


@api_view(['post'])
def add_case(request):
    data = JSONParser().parse(request)
    case_name = data.get('case_name')
    user_id = data.get('user_id')
    priority = data.get('priority')
    pre_condition = data.get('pre_condition')
    plan_id = data.get('plan_id')
    case_type = data.get('case_type')
    review_status = data.get('review_status')
    suggestion = data.get('suggestion')
    Test_Case(case_name=case_name, user_id=user_id, priority=priority, pre_condiction=pre_condition, plan_id=plan_id,
              case_type=case_type, review_status=review_status, suggestion=suggestion).save()
    return JsonResponse({
        'code': 200,
        'msg': '用例添加成功'
    })


@api_view(['put'])
def update_case(request):
    data = JSONParser().parse(request)
    case_name = data.get('case_name')
    suggestion = data.get('suggestion')

    def is_empty(n):
        return n is None or str(n).strip() == ''

    if is_empty(case_name):
        return JsonResponse({
            'msg': '项目名称不能为空'
        })

    d = Test_Case.objects.filter(case_name=case_name)
    if d.exists() is False:
        return JsonResponse({
            "code": 404,
            "msg": "该项目不存在",
        }, status=404)
    d = Test_Case.objects.get(case_name=case_name)
    d.suggestion = suggestion
    d.save()
    return JsonResponse({
        "code": 200,
        "msg": "项目名称修改成功",
    }, status=200)


@api_view(['delete'])
def dle_case(request):
    data = JSONParser().parse(request)
    case_name = data.get('case_name')

    def is_empty(n):
        return n is None or str(n).strip() == ''

    if is_empty(case_name):
        return JsonResponse({
            'msg': '项目名称不能为空'
        })
    d = Test_Case.objects.filter(case_name=case_name).first()
    d.delete()
    return JsonResponse({
        "code": 200,
        "msg": "删除成功",
    })
